package com.jch.dm8_thread_specific_storage.example;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

// 强随机数生成器
public class ThreadSpecificSecureRandom {

    public static final ThreadSpecificSecureRandom INSTANCE = new ThreadSpecificSecureRandom();

    /*
    * SECURE_RANDOM相当于模式角色：ThreadSpecificStorage.TSObjectProxy
    * SecureRandom相当于模式角色：ThreadSpecificStorage.TSObject
    */
    private static final ThreadLocal<SecureRandom> SECURE_RANDOM = new ThreadLocal<SecureRandom>(){
        @Override
        protected SecureRandom initialValue() {
            SecureRandom secureRandom;
            try{
                secureRandom = SecureRandom.getInstance("SHA1PRNG");
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
                secureRandom = new SecureRandom();
            }
            return secureRandom;
        }
    };

    private ThreadSpecificSecureRandom(){
    }

    public int nextInt(int upperBound){
        SecureRandom secureRandom = SECURE_RANDOM.get();
        return secureRandom.nextInt(upperBound);
    }

    public void setSeed(long seed){
        SecureRandom secureRandom = SECURE_RANDOM.get();
        secureRandom.setSeed(seed);
    }
}
